import {
    API
} from "../../../utils/fireapi.js";
import {
    Config
} from '../../../utils/config'
import {
    Utils
} from "../../../utils/util.js";
// 小程序配置信息
const app = getApp();
Page({
    data: {
        // 界面定制化的配置参数
        // pageSet: app.globalData.settings.compress,
        // canvas组件用于图片操作,绘制\下载等
        canvasComponent: undefined,
        // 下载组件
        downloadComp: undefined,
        // 选中的压缩尺寸选项,1:100k以下,2:100-200k
        selected: "1",
        // 从相册选择的原始图片
        sourceImg: undefined,
        // 压缩后目标尺寸(不大于该尺寸)
        targetSize: 1024,
        // 后端替换背景服务功能标识
        identity: new Object(),
        // 显示正在压缩的等待界面
        showWaitPage: false,
        //下载图片前处理函数(例如:修改图片dpi等)
        beforeFun: new Function(),
        //用于标识文件唯一性,支付成功后,相同标识的文件可以重复下载
        imgRandom: 0,
        // 等待界面参数
        waitItem:{},

    },
    /** 从相册选择则图片进行处理 */
    chooseImage() {
        let _this = this;
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album'],
            sizeType: ['original'],
            success(res) {
                _this.setData({
                    'sourceImg.src': res.tempFiles[0].tempFilePath,
                    'sourceImg.size': res.tempFiles[0].size,
                    imgRandom: (Math.random() * 1000).toFixed(0).toString()
                })
            }
        })
    },

    /**压缩图片 */
    compress(imgSrc, width, height, quality) {
        let canvasComp = this.data.canvasComponent;
        return new Promise(async (resolve, reject) => {
            let compressedImgUrl = await API.compressImage(canvasComp, imgSrc, width, height, quality);
            wx.getFileInfo({
                filePath: compressedImgUrl,
                success(info) {
                    resolve({
                        src: compressedImgUrl,
                        targetSize: info.size
                    })
                },
                fail(err){
                    reject(err)
                }
            })
        })
    },

    /**根据页面选中的文件大小按钮,设置文件目标压缩尺寸 */
    selected(e) {
        const item = e.detail.data;
        this.setData({
            selected: item.id,
            targetSize: 1024 * parseInt(item.id) * 100     // 100k或200k
        })
    },
    
    /** 下载组件下载前的回调函数,对图片进行处理 */
    async beforeDownload(imgUrl) {
        this.beginCompress();
        return new Promise(async (resolve, reject) => {
                // 原图信息
                const srcImage = this.data.sourceImg;
                // 目标尺寸
                const tarSize = this.data.targetSize;
                // 大于目标尺寸,进行压缩处理
                if (srcImage.size * 1024 > tarSize) {
                    const imgInfo = await Utils.getImgInfo(imgUrl);
                    let ratio = 1;
                    let result = await this.compress(srcImage.src, imgInfo.width, imgInfo.height, ratio);
                    while (result.size > tarSize && ratio > 0.6) {
                        ratio -= 0.1;
                        result = await this.compress(result.src, imgInfo.width, imgInfo.height, ratio);
                    }
                    // 保存压缩后结果
                    srcImage.src = result.src;
                }
                resolve(srcImage.src);
                this.endCompress();
            }

        )
    },
    // /**开始压缩事件 */
    beginCompress() {
        this.setData({
            showWaitPage: true
        })

    },
    /** 下载完成后处理完成事件 */
    endCompress() {
        this.setData({
            showWaitPage: false
        })
    },
    /**设置显示或隐藏,正在处理等待界面 */
    showWaitModel(){
        this.setData({
            showWaitPage: !this.data.showWaitPage
        })
    },
    onLoad() {
        const serverData = app.globalData.serverData;
        const waitItem={
            img:serverData.config.waitPageImg,
            text:serverData.config.waitPageTxt
        };
        const identity = serverData.funcPrice[Config.IDENTITY_COMPRESS];
        this.setData({
            identity: identity,
            waitItem:waitItem,
            beforeFun: this.beforeDownload
        })
    },
    onReady() {
        // 获取自定义组件对象
        this.data.canvasComponent = this.selectComponent("#compress-canvas");
        this.data.downloadComp = this.selectComponent("#compress-download");
    },

})